package com.net.xpay.core.helper;

import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.net.xpay.common.domain.open.OpenApiApp;
import com.net.xpay.common.manager.open.OpenApiAppManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 2020/6/28 10:39

 */
@Slf4j
@Component
public class OpenSignerCheckHelper {
    @Autowired
    private OpenApiAppManager openApiAppManager;

    public OpenApiApp checkSign(String appkey, String timestamp, String signature) {
        if (Strings.isNullOrEmpty(appkey)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "appkey不能为空");
        }

        if (Strings.isNullOrEmpty(timestamp)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "timestamp不能为空");
        }
        if (Strings.isNullOrEmpty(signature)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "signature不能为空");
        }
        OpenApiApp openApiApp = openApiAppManager.findByAppkey(appkey);
        if (openApiApp == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "应用不存在");
        }
        String secret = openApiApp.getSecret();

        String correctSign = Hashing.md5().hashString(appkey + secret + timestamp, Charsets.UTF_8).toString();
        if (!signature.equalsIgnoreCase(correctSign)) {
            log.warn("open checkSign signature error|appkey={}|secret={}|timestamp={}|signature={}", appkey, secret, timestamp, signature);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "签名错误");
        }
        return openApiApp;
    }
}
